layui.use(['form','tree','element','laydate','table','laytpl','treeGrid','layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;
    var laydate = layui.laydate;

    //获取路径参数
    var request = GetRequest();

    $.get('/record/monitor/query?produceBatchId=' + request.id + '&processId=' + request.processId + '&page=0&limit=100',function (data) {
        if (data.data.length != 0) {
            var monitor = data.data[0];
            var date = new Date(monitor.createDate);
            var curdate = new Date();
            /*console.log(d.acquisitionTime);*/
            var downAcquisitionTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()+ "T" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "Z";
            var upAcquisitionTime = curdate.getFullYear() + '-' + (curdate.getMonth() + 1) + '-' + curdate.getDate()+ "T" + curdate.getHours() + ":" + curdate.getMinutes() + ":" + curdate.getSeconds() + "Z";
            console.log(upAcquisitionTime);
            //设备列表
            $.each(data.data,function (i,ele) {
                $.get('/equipment/' + ele.equipmentId,function (equipment) {
                    $("#equipment-list").append('<option value="'+ ele.equipmentId +'">'+ equipment.name +'</option>');
                    $("#equipment-list2").append('<option value="'+ ele.equipmentId +'">'+ equipment.name +'</option>');
                    form.render('select');
                });
            });

            //刷新设备对应的数据采集项
            form.on('select(equipment-list)',function (data) {
                $.get("/equipment/channel/query?equipmentId=" + data.value,function (data) {
                    $("#checkItem").html("");
                    $("#checkItem").append('<option value="">请选择</option>');
                    $.each(data.data,function (i,ele) {
                        $("#checkItem").append('<option value="'+ ele.collectChannelApplicateTypeId +'">'+ ele.channelName +'</option>');
                    });
                    form.render('select');
                });
            });

            //列表数据
            var option = {
                elem: '#tableList',
                url : '/search/datarecord/page/query?equipmentId=' + monitor.equipmentId + '&downAcquisitionTime=' + downAcquisitionTime + '&upAcquisitionTime=' + upAcquisitionTime,
                cellMinWidth : 95,
                page : true,
                /*height : "full-150",*/
                limits : [10,15,20,25],
                limit : 15,
                id : "listTable",
                cols : [[
                    {type: "checkbox", fixed:"left", width:50},
                    {field: 'equipmentName', title: '所属设备', minWidth:100, align:"center"},
                    {field: 'channelNo', title: '通道号', minWidth:200, align:'center'},
                    {field: 'checkItemName', title: '采集项', minWidth:100, align:"center"},
                    {field: 'processedData', title: '数据',  align:'center'},
                    {field: 'unit', title: '单位',  align:'center'},
                    {field: 'acquisitionTime', title: '采集时间', align:'center',minWidth:150,sort:true, templet:function(d){
                            //处理时间
                            var date = new Date(d.acquisitionTime);
                            /*console.log(d.acquisitionTime);*/
                            return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()+ " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                        }
                    },
                    {field: 'reportingTime', title: '上报时间', align:'center',minWidth:150,sort:true, templet:function(d){
                            //处理时间
                            var date = new Date(d.reportingTime);
                            /*console.log(d.acquisitionTime);*/
                            return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()+ " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                        }
                    },
                    {title: '操作', minWidth:175, templet:'#tableListBar',fixed:"right",align:"center"}
                ]],
                done: function (res, curr, count) {
                    /*layer.close(myindex);*/
                }
            };

            //设备列表
            tableIns = table.render(option);

            //搜索设备信息
            $(".search_btn").on("click",function(){
                var equipmentId = $("#equipment-list").val();
                var checkItemId = $("#checkItem").val();
                var upAcquisitionTime = $("#upAcquisitionTime").val();
                var downAcquisitionTime = $("#downAcquisitionTime").val();
                console.log(monitor.createDate);
                if (new Date(downAcquisitionTime).getTime() < monitor.createDate) {
                    layer.msg("暂无数据！");
                    return;
                }
                var searchObj = {};
                if(equipmentId == ''){
                    layer.msg("请选择搜索设备");
                    return;
                }
                searchObj.equipmentId = equipmentId;
                searchObj.checkItemId = checkItemId;
                if (upAcquisitionTime != null && upAcquisitionTime != "") {
                    searchObj.upAcquisitionTime = upAcquisitionTime + "T00:00:00Z";
                }
                if (downAcquisitionTime != null && downAcquisitionTime != "") {
                    searchObj.downAcquisitionTime = downAcquisitionTime + "T00:00:00Z";
                }
                option.url = '/search/datarecord/page/query';
                option.method = 'post';
                option.where = searchObj;
                table.render(option);
            });

            //初始化统计图，循环遍历出当前设备下所有统计的数据
            $("#searchBtn").click(function () {
                //获取选择查询的范围
                var coure = $("#date-coure").val();
                var curdate = new Date(monitor.createDate);//测试一下1546355252000
                var endSolrDate = getSolrDate(curdate);//开始时间
                var enddate = new Date(curdate.getTime() - 24*60*60*1000);
                if (coure == 0) {
                    enddate = new Date(curdate.getTime() - 24*60*60*1000);
                } else if(coure == 1) {
                    enddate = new Date(curdate.getTime() - 7*24*60*60*1000);
                } else if(coure == 2) {
                    enddate = new Date(curdate.getTime() - 30*24*60*60*1000);
                }

                var startSolrDate = getSolrDate(enddate);//结束时间
                var equipmentId = $("#equipment-list2").val();
                console.log(equipmentId);
                if(equipmentId == ''){
                    layer.msg("请选择搜索设备");
                    return;
                }

                var searchObj = {};
                searchObj.page = 0;
                searchObj.limit = 20000;//设置默认最大查询范围
                searchObj.equipmentId = equipmentId;
                // searchObj.checkItemId = checkItemId;
                searchObj.downAcquisitionTime = startSolrDate;
                searchObj.upAcquisitionTime = endSolrDate;
                //开启加载动画
                $("#loading").show();
                /*window.myindex = layer.load(2);*/
                $.get("/search/datarecord/page/query?",searchObj,function (data) {
                    //当前设备的检测项目
                    var checkItemArr = [];
                    if (data.data.length <= 0) {
                        //关闭加载动画
                        $("#loading").hide();
                        /*layer.close(myindex);*/
                        layer.msg("没有找到数据！换一个时间范围试试？");
                        return;
                    }
                    $.each(data.data,function (i, ele) {
                        if (contains(checkItemArr,ele.checkItemId) != -1 && ele.checkItemName != "设备信息") {
                            checkItemArr.unshift(ele.checkItemId);
                        }
                    });
                    $("#echart-content").html("");
                    for (var i = 0;i < checkItemArr.length;i++) {
                        //x轴时间组件
                        var xAxisdataArr = [];
                        var seriesArr = [];
                        var checkMessage = {};
                        $.each(data.data,function (j, ele) {
                            if (checkItemArr[i] == ele.checkItemId) {
                                var date = new Date(ele.acquisitionTime);
                                var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                                xAxisdataArr.unshift(dateStr);
                                seriesArr.unshift(ele.processedData);
                                checkMessage.title = ele.checkItemName + "趋势";
                                checkMessage.legendData = ele.checkItemName;
                                checkMessage.seriesName = ele.checkItemName;
                                checkMessage.yAxisformatter = ele.unit;

                            }
                        });
                        //初始化统计图
                        initChart(i,xAxisdataArr,seriesArr,checkMessage);
                    }
                });
            });

            /**
             * 初始化统计图
             * @param index
             * @param xAxisdataArr
             * @param seriesArr
             * @param checkMessage
             */
            function initChart(index,xAxisdataArr, seriesArr,checkMessage) {
                //关闭加载动画
                /*layer.close(myindex);*/
                $("#loading").hide();
                var innerHtml = '<div class="layui-elem-quote layui-quote-nm magb0 echart-box">' +
                    '                <div id="line-chart-'+ index +'" style="margin-top:10px;width: 95%; height: 400px;">' +
                    '                </div>' +
                    '            </div>';
                $("#echart-content").append(innerHtml);
                //折线图
                var lineChart = echarts.init(document.getElementById('line-chart-' + index));
                var option = {
                    title: {
                        text: checkMessage.title,
                        subtext: ' '
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data:[checkMessage.legendData]
                    },
                    toolbox: {
                        show: true,
                        feature: {
                            dataZoom: {
                                yAxisIndex: 'none'
                            },
                            dataView: {readOnly: false},
                            magicType: {type: ['line', 'bar']},
                            restore: {},
                            saveAsImage: {}
                        }
                    },
                    xAxis:  {
                        type: 'category',
                        boundaryGap: false,
                        data: xAxisdataArr
                    },
                    yAxis: {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value} ' + checkMessage.yAxisformatter
                        }
                    },
                    series: [
                        {
                            name:checkMessage.seriesName,
                            type:'line',
                            data:seriesArr,
                            markPoint: {
                                data: [
                                    {type: 'max', name: '最大值'},
                                    {type: 'min', name: '最小值'}
                                ]
                            },
                            markLine: {
                                data: [
                                    {type: 'average', name: '平均值'}
                                ]
                            }
                        }
                    ]
                };
                lineChart.setOption(option);
            }


        } else {
            /*layer.msg('请先添加设备');*/
        }
    });

    laydate.render({
        elem: '#downAcquisitionTime'
    });
    laydate.render({
        elem: '#upAcquisitionTime'
    });
    //检测项目数据
    $.get("/checkitem/list",function (data) {
        $.each(data.data,function (i,ele) {
            $("#checkItem").append('<option value="'+ ele.id +'">'+ ele.name +'</option>');
        });
        form.render('select');
    });

    //添加设备
    $(".addBtn").click(function () {
        var index = layui.layer.open({
            title : "请选择设备",
            type : 2,
            area: ['400px','250px'],
            content : "tracerecordMonitorAQ?produceBatchId=" + request.id + '&processId=' + request.processId,
            success : function(){
                setTimeout(function(){
                    layui.layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500);
            }
        });
    });


    //列表操作
    table.on('tool(tableList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
            var index = layui.layer.open({
                title : "查看记录详细信息",
                type : 2,
                content : "datarecordView?id=" + data.id,
                area: ['100%',$(document).height() - 30 + 'px'],
                success : function(){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回设备列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize",function(){
                layui.layer.full(index);
            });
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此设备？',{icon:3, title:'提示信息'},function(index){
                $.get("/datarecord/delete?id=" + data.id,function(data){
                    if (data.code == 200) {
                        layer.msg("删除成功！");
                    } else {
                        layer.msg("删除失败，请重试！");
                    }
                    tableIns.reload();
                    layer.close(index);
                });
            });
        }
    });

    /**
     * 获取路径中的参数
     * @returns {Object}
     */
    function GetRequest() {
        var url = location.search;         //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }

    /**
     * 判断数组中是否存在元素
     * @param arr
     * @param obj
     * @returns {number}
     */
    function contains(arr, obj) {
        if (arr.length != 0) {
            for (var i = 0;i < arr.length;i++) {
                if(arr[i] == obj) {
                    return -1;
                }
            }
        }
        return 0;
    }

    /**
     * 获取当前时间，以solr中date的格式 2018-08-27T02:28:58Z
     * @param date
     * @returns {string}
     */
    function getSolrDate(date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
        var day = date.getDate() >= 10 ? date.getDate() : "0" + date.getDate();
        var hour = date.getHours() >= 10 ? date.getHours() : "0" + date.getHours();
        var minutes = date.getMinutes() >= 10 ? date.getMinutes() : "0" + date.getMinutes();
        var seconds = date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds();
        var dateStr = year + '-' + month + '-' + day + 'T' + hour + ':' + minutes + ':' + seconds + 'Z';
        return dateStr;
    }

});